package com.itheima.bakery.demos.web.service.impl;

import com.itheima.bakery.demos.web.Repositories.*;
import com.itheima.bakery.demos.web.model.*;
import com.itheima.bakery.demos.web.service.CartService;
import com.itheima.bakery.demos.web.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.sql.Date;
import java.sql.Timestamp;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderRepository orderRepository;

    @Autowired
    private OrderDetailRepository orderDetailRepository;

    @Autowired
    private CartItemRepository cartItemRepository;
    @Autowired
    private InventoryRepository inventoryRepository;
    @Autowired
    private ShippingAddressRepository shippingAddressRepository;

    private static final Logger logger = LoggerFactory.getLogger(OrderServiceImpl.class);
    @Override
    public List<Order> findAllOrders() {
        return orderRepository.findAll();
    }

    @Override
    public Optional<Order> findOrderById(Integer id) {
        return orderRepository.findById(id);
    }

    @Override
    public Order saveOrder(Order order) {
        return orderRepository.save(order);
    }


    @Override
    public boolean deleteOrder(Integer id) {
        Optional<Order> orderOptional = orderRepository.findById(id);
        if (orderOptional.isPresent()) {
            try {
                orderRepository.deleteById(id);
                return true;
            } catch (Exception e) {
                // 处理可能的异常，例如日志记录
                return false;
            }
        } else {
            return false;
        }
    }

    @Override
    @Transactional
    public void updateOrderTotal(Integer orderId) {
        BigDecimal totalAmount = orderRepository.findById(orderId)
                .map(order -> calculateTotalAmount(order.getDetails()))
                .orElse(BigDecimal.ZERO);
        orderRepository.findById(orderId).ifPresent(order -> {
            order.setTotalAmount(totalAmount);
            orderRepository.save(order);
        });
    }

    // 使用OrderDetail列表计算总金额的方法
    private BigDecimal calculateTotalAmount(List<OrderDetail> details) {
        return details.stream()
                .map(OrderDetail::getSubtotal)
                .reduce(BigDecimal.ZERO, BigDecimal::add);
    }

    // 使用CartItem列表计算总金额的方法
    private BigDecimal calculateTotalAmountFromCartItems(List<CartItem> cartItems) {
        if (cartItems == null || cartItems.isEmpty()) {
            return BigDecimal.ZERO;
        }
        return cartItems.stream()
                .map(CartItem::getSubtotal)
                .reduce(BigDecimal.ZERO, BigDecimal::add);
    }


    public List<Order> getOrdersByUserId(Integer userId) {
        return orderRepository.findByUserID(userId);
    }

    @Override
    @Transactional
    public Integer createOrderAndDetails(Integer userId, List<CartItem> cartItems) {
        try {
            // 创建订单对象
            Order order = new Order();
            order.setUserID(userId);
            order.setStatus("未支付");
            order.setCreateTime(new Timestamp(System.currentTimeMillis()));
            // 使用CartItem列表计算订单总金额
            BigDecimal totalAmount = calculateTotalAmountFromCartItems(cartItems);
            order.setTotalAmount(totalAmount); // 确保设置totalAmount

            // 自动生成subject
            order.setSubject(generateSubjectFromCartItems(cartItems));

            // 保存订单
            Order savedOrder = orderRepository.save(order);

            // 为每个购物车项创建订单详情
            for (CartItem cartItem : cartItems) {
                OrderDetail orderDetail = new OrderDetail();
                orderDetail.setOrder(savedOrder);
                orderDetail.setProduct(cartItem.getProduct());
                orderDetail.setQuantity(cartItem.getQuantity());
                orderDetail.setUnitPrice(cartItem.getProduct().getPrice());
                orderDetail.setSubtotal(cartItem.getSubtotal());
                orderDetailRepository.save(orderDetail);
            }

            // 清空数据库中的购物车项
            cartItemRepository.deleteByUserId(userId);

            return savedOrder.getOrderID();
        } catch (Exception e) {
            // 记录异常信息
            logger.error("Error during order creation: ", e);
            // 根据需要抛出自定义异常或处理异常
            throw new RuntimeException("Error creating order", e);
        }
    }

    private String generateSubjectFromCartItems(List<CartItem> cartItems) {
        StringBuilder subjectBuilder = new StringBuilder();
        for (CartItem cartItem : cartItems) {
            if (subjectBuilder.length() > 0) {
                subjectBuilder.append(", ");
            }
            subjectBuilder.append(cartItem.getProduct().getName());
        }
        return subjectBuilder.toString();
    }


    private void clearSelectedCartItems(Integer userId, Set<Integer> productIdsToRemove, HttpSession session) {
        // 从session中获取购物车
        Cart cart = (Cart) session.getAttribute("cart");
        if (cart != null) {
            cart.getItems().removeIf(item -> productIdsToRemove.contains(item.getProductId()));
            session.setAttribute("cart", cart);
        }

        // 从数据库中删除已选择的购物车项
        cartItemRepository.deleteByUserIdAndProductIds(userId, productIdsToRemove);
    }
    @Override
    public List<OrderDetail> findOrderDetailsByOrderId(Integer orderId) {
        return orderDetailRepository.findByOrder_OrderID(orderId);
    }

    @Override
    public Order updateOrderAddress(Integer orderId, Integer addressId) {
        Order order = orderRepository.findById(orderId)
                .orElseThrow(() -> new RuntimeException("Order not found with ID: " + orderId));

        ShippingAddress address = shippingAddressRepository.findById(addressId)
                .orElseThrow(() -> new RuntimeException("Shipping address not found with ID: " + addressId));

        order.setShippingAddress(address);
        return orderRepository.save(order);
    }
    @Override
    @Transactional
    public void updateOrderStatus(Integer orderId, String status, String alipayNo, Timestamp payTime) {
        Optional<Order> orderOptional = orderRepository.findById(orderId);
        if (orderOptional.isPresent()) {
            Order order = orderOptional.get();
            order.setStatus(status);
            order.setAlipayNo(alipayNo);
            order.setPayTime(payTime);
            orderRepository.save(order);
        } else {
            throw new RuntimeException("Order not found with ID: " + orderId);
        }
    }
    @Transactional(readOnly = true)

    public Optional<ShippingAddress> getShippingAddressByOrderID(Integer orderID) {
        logger.info("Fetching ShippingAddress for Order ID: {}", orderID);
        return orderRepository.findById(orderID)
                .flatMap(order -> {
                    if (order != null && order.getShippingAddress() != null) {
                        return shippingAddressRepository.findById(order.getShippingAddress().getId());
                    } else {
                        return Optional.empty();
                    }
                });
    }
}